package com.yfbao.horizon.schedule.tk.thread;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadLockMonitor {

    private final ThreadMXBean threadMXBean;
    private volatile String lastLockInfo; // 缓存锁信息

    public ThreadLockMonitor() {
        this.threadMXBean = ManagementFactory.getThreadMXBean();
        startMonitoring();
    }

    private void startMonitoring() {
        ScheduledExecutorService scheduler =new ScheduledThreadPoolExecutor(1,
                new ThreadFactoryBuilder().setNamePrefix("CtpMonitor-").build());

        // 每 5 秒采集一次锁信息
        scheduler.scheduleAtFixedRate(this::collectLockInfo, 0, 5, TimeUnit.SECONDS);
    }

    private void collectLockInfo() {
        StringBuilder lockInfo = new StringBuilder();
        long[] threadIds = threadMXBean.getAllThreadIds();
        for (long threadId : threadIds) {
            ThreadInfo threadInfo = threadMXBean.getThreadInfo(threadId);
            if (threadInfo != null) {
                lockInfo.append("Thread: ").append(threadInfo.getThreadName()).append("\n");
                lockInfo.append("Lock owner: ").append(threadInfo.getLockOwnerName()).append("\n");
                lockInfo.append("Blocked count: ").append(threadInfo.getBlockedCount()).append("\n");
                lockInfo.append("Blocked time: ").append(threadInfo.getBlockedTime()).append("\n");
                lockInfo.append("Locked monitors: ").append(threadInfo.getLockedMonitors().length).append("\n");
                lockInfo.append("Locked synchronizers: ").append(threadInfo.getLockedSynchronizers().length).append("\n\n");
            }
        }
        lastLockInfo = lockInfo.toString(); // 更新缓存
    }

    public String getLastLockInfo() {
        return lastLockInfo;
    }

//    public static void main(String[] args) throws InterruptedException {
//        OptimizedLockMonitor monitor = new OptimizedLockMonitor();
//        // 模拟应用运行
//        while (true) {
//            System.out.println(monitor.getLastLockInfo());
//            Thread.sleep(5000); // 每 5 秒打印一次锁信息
//        }
//    }
}
